import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { Card, Col, message, Row, Space } from 'antd';
import React, { useRef } from 'react';
import { useModel, useRequest } from 'umi';

import md5 from 'blueimp-md5';

import * as api from '@/services/account';
import { PageContainer } from '@ant-design/pro-components';

const UserCenter: React.FC = () => {
  console.log('========= account index ========');

  const { initialState, setInitialState } = useModel('@@initialState');
  // console.log(initialState);
  // const { currentUser } = initialState;
  // if (!currentUser || !currentUser.name) {
  //   return false;
  // }

  const formRef = useRef<ProFormInstance>();

  const { loading } = useRequest(async () => {
    Promise.resolve({
      loading: false,
    });
  });

  const handleFormSubmit = async (record: API.UserModel) => {
    // console.log('record', record);
    // console.log('formRef.checkedRightIds: ', checkedRightIds);
    let op = formRef.current?.getFieldValue('oldPassword');
    let np = formRef.current?.getFieldValue('newPassword');
    if (op && np && op !== '' && np !== '') {
      op = md5(op);
      np = md5(np);
      let result = await api.changePsw({ oldPsw: op, newPsw: np });

      if (result && result.success === true) {
        message.success('提交成功');
        formRef.current?.resetFields([
          'oldPassword',
          'newPassword',
          'newCfmPassword',
        ]);
      }
    } else {
      message.error('密码不能为空');
    }
  };

  //新旧密码不能一样
  const handleCheckPwd = async (rules: any, value: any, callback: any) => {
    let cfmPwd = formRef.current?.getFieldValue('oldPassword');
    if (cfmPwd && cfmPwd == value) {
      callback(new Error('新旧密码不能一样'));
    } else {
      // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
      callback();
    }
  };

  //确认密码校验一致
  const handleCfmPwd = async (rules: any, value: any, callback: any) => {
    let newPassword = formRef.current?.getFieldValue('newPassword');
    let newCfmPassword = formRef.current?.getFieldValue('newCfmPassword');
    if (newPassword && newCfmPassword && newPassword !== newCfmPassword) {
      callback(new Error('两次密码输入不一致'));
    } else {
      // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
      callback();
    }
  };

  return (
    <PageContainer>
      {loading && <Card style={{ minHeight: 640 }} loading={loading} />}
      {!loading && (
        <Card>
          <ProForm<API.UserModel>
            formRef={formRef}
            layout="horizontal"
            style={{ margin: 'auto', marginTop: 8, maxWidth: 600 }}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 18 }}
            initialValues={initialState?.currentUser}
            submitter={{
              render: (props, doms) => {
                return (
                  <Row>
                    <Col span={18} offset={4}>
                      <Space>
                        {doms[1]}
                        {doms[0]}
                      </Space>
                    </Col>
                  </Row>
                );
              },
            }}
            onFinish={handleFormSubmit}
          >
            <ProFormText name="name" label="名称" readonly={true} />
            <ProFormText name="username" label="用户名" readonly={true} />
            <ProFormText.Password
              name="oldPassword"
              label="旧密码"
              rules={[{ required: true, message: '请输入旧密码' }]}
              placeholder="请输入旧密码"
            />
            <ProFormText.Password
              name="newPassword"
              label="新密码"
              rules={[
                { required: true, message: '请输入新密码' },
                {
                  validator: (rules, value, callback) => {
                    handleCheckPwd(rules, value, callback);
                  },
                },
                {
                  validator: (rules, value, callback) => {
                    handleCfmPwd(rules, value, callback);
                  },
                },
              ]}
              placeholder="请输入新密码"
            />
            <ProFormText.Password
              name="newCfmPassword"
              label="确认新密码"
              rules={[
                { required: true, message: '请输入确认新密码' },
                {
                  validator: (rules, value, callback) => {
                    handleCfmPwd(rules, value, callback);
                  },
                },
              ]}
              placeholder="请输入确认新密码"
            />
          </ProForm>
        </Card>
      )}
    </PageContainer>
  );
};

export default UserCenter;
